package com.example.jiangkt.ergongyi.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.jiangkt.ergongyi.R;
import com.example.jiangkt.ergongyi.util.AlertShow;
import com.example.jiangkt.ergongyi.util.CustomAction;
import com.example.jiangkt.ergongyi.util.UserUtil;

import java.util.HashMap;
import java.util.Map;

public class UpUserActivity extends Activity implements View.OnClickListener {
    private EditText et_email;
    private EditText et_userpwd;
    private EditText et_conpwd;
    private Button bt_submit;
    private Button bt_submit_email;
    private ImageView iv_email_cancel;
    private TextView tv_email_warn;
    private TextView tv_forget_warn;
    private EditText et_code;
    private String email = "";
    private String userPwd = "";
    private String confirmPwd = "";
    private String emailCode = "";
    private LinearLayout ll_email_code;
    private ActionBar actionBar;
    private UpReceiver upReceiver;
    private String result;
    private Map<String, Object> map;
    private Map<String, Object> mapConfirm;
    private AlertDialog emailCodeDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_up_user);

        this.init();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (emailCodeDialog!=null){
            emailCodeDialog.dismiss();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (emailCodeDialog!=null){
            emailCodeDialog.dismiss();
        }
        this.unregisterReceiver(upReceiver);
    }

    private void init() {
        et_email = findViewById(R.id.uu_et_email);
        et_userpwd = findViewById(R.id.uu_et_addpwd);
        et_conpwd = findViewById(R.id.uu_et_conpwd);
        tv_forget_warn = findViewById(R.id.tv_forget_warn);
        tv_forget_warn.setTextColor(getApplication().getResources().getColor(R.color.colorLogin1));

        bt_submit = findViewById(R.id.uu_bt_submit);
        bt_submit.setOnClickListener(UpUserActivity.this);

        actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setIcon(R.drawable.select_back);
        int color = Color.parseColor("#1296db");
        ColorDrawable drawable = new ColorDrawable(color);
        actionBar.setBackgroundDrawable(drawable);

        IntentFilter filter = new IntentFilter(CustomAction.UP_ACTION);
        upReceiver = new UpReceiver();
        registerReceiver(upReceiver, filter);
    }

    private boolean upUser(String email, String userPwd, String confirmPwd) {
        if (!AlertShow.isEmail(email)) {
            tv_forget_warn.setText("邮箱地址不符合");
        } else if (!AlertShow.isPassword(UserUtil.decrypt(userPwd))) {
            tv_forget_warn.setText("密码不符合");
        } else if (!UserUtil.decrypt(userPwd).equals(UserUtil.decrypt(confirmPwd))) {
            tv_forget_warn.setText("两次密码输入不一致");
        } else {
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.uu_bt_submit:
                email = et_email.getText().toString();
                userPwd = UserUtil.encrypt(et_userpwd.getText().toString());
                confirmPwd = UserUtil.encrypt(et_conpwd.getText().toString());

                if (upUser(email, userPwd, confirmPwd)) {
                    AlertShow.dialog = ProgressDialog.show(this, null, "正在请求中...");
                    map = new HashMap<>();
                    map.put("reqType", "firstUpReq");
                    map.put("email", email);

                    Intent intent = new Intent(CustomAction.SERVICE_ACTION);
                    intent.putExtra("request", JSONObject.toJSON(map).toString());
                    sendBroadcast(intent);
                }
                break;
            case R.id.submit_email_code:
                // 绑定提交验证码按钮
                et_code = ll_email_code.findViewById(R.id.et_emailcode);
                emailCode = et_code.getText().toString();
                if (!AlertShow.isEmailCode(emailCode)) {
                    tv_email_warn.setText("格式不正确");
                } else {
                    mapConfirm = new HashMap<>();
                    mapConfirm.put("reqType", "secondUpReq");
                    mapConfirm.put("email", email);
                    mapConfirm.put("emailCode", emailCode);
                    mapConfirm.put("userPwd", userPwd);

                    Intent intent = new Intent(CustomAction.SERVICE_ACTION);
                    intent.putExtra("request", JSONObject.toJSON(mapConfirm).toString());
                    sendBroadcast(intent);
                }
                break;
            case R.id.iv_email_cancel:
                emailCodeDialog.cancel();
                break;

        }
    }

    public class UpReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            result = intent.getStringExtra("up");

            if ("501".equals(result)) {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                ll_email_code = (LinearLayout) UpUserActivity.this.getLayoutInflater().inflate(R.layout.alert_email_code, null);
                bt_submit_email = ll_email_code.findViewById(R.id.submit_email_code);
                bt_submit_email.setOnClickListener(UpUserActivity.this);
                iv_email_cancel = ll_email_code.findViewById(R.id.iv_email_cancel);
                iv_email_cancel.setOnClickListener(UpUserActivity.this);
                tv_email_warn = ll_email_code.findViewById(R.id.tv_email_warn);
                tv_email_warn.setTextColor(getApplication().getResources().getColor(R.color.colorLogin1));
                emailCodeDialog = new AlertDialog.Builder(UpUserActivity.this)
                        .setView(ll_email_code)
                        .create();
                emailCodeDialog.show();

                DisplayMetrics dm = new DisplayMetrics();
                //获取屏幕信息
                UpUserActivity.this.getWindowManager().getDefaultDisplay().getMetrics(dm);

                int screenWidth = dm.widthPixels;

                int screenHeigh = dm.heightPixels;
                WindowManager.LayoutParams params =

                        emailCodeDialog.getWindow().getAttributes();//获取dialog信息

                params.width = screenWidth - 20;

                params.height = screenHeigh / 3;

                emailCodeDialog.getWindow().setAttributes(params);//设置大小

                new CountDownTimer(60 * 1000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        bt_submit.setText("还剩" + millisUntilFinished / 1000 + "秒");
                        bt_submit.setEnabled(false);
                    }

                    @Override
                    public void onFinish() {
                        bt_submit.setText("修改密码");
                        bt_submit.setEnabled(true);
                    }
                }.start();
            } else if ("401".equals(result)) {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                Toast.makeText(UpUserActivity.this, "成功修改密码", Toast.LENGTH_SHORT).show();
                UserUtil.saveLoginInfo(UpUserActivity.this, email, userPwd);
                Intent startActivity = new Intent(UpUserActivity.this, LoginActivity.class);
                startActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                UpUserActivity.this.startActivity(startActivity);
                UpUserActivity.this.finish();
            } else if ("402".equals(result)) {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                tv_email_warn.setText("验证码错误");
            } else if ("502".equals(result)) {
                if (AlertShow.dialog != null) {
                    AlertShow.dialog.dismiss();
                }
                tv_forget_warn.setText("该邮箱未注册");
            }
            result = null;
        }
    }
}
